package com.cloud.diffdemo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cloud.diffdemo.adapter.TestAdapter;
import com.cloud.diffdemo.callback.DiffCallBack;
import com.cloud.diffdemo.model.TestBean;

import java.util.ArrayList;
import java.util.List;

/**
 * @auth: njb
 * @date: 2024/11/20 23:46
 * @desc: 描述
 */
public class MainActivity1 extends AppCompatActivity {
    private List<TestBean> mDatas;
    private RecyclerView mRv;
    private TestAdapter mAdapter;
    private Button btnRefresh;
    private String url = "http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960";
    private List<TestBean> mNewDatas;
    private String[] userNames = {"Jack,Tom,John,LiLi"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        mRv = findViewById(R.id.recyclerView);
        btnRefresh = findViewById(R.id.btn_refresh);
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TestAdapter(this, mDatas);
        mRv.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
        mRv.setAdapter(mAdapter);
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh(v);
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mDatas = new ArrayList<>();
        mDatas.add(new TestBean("Tome", "今天天气很好，出来钓鱼", R.drawable.ic_launcher_background, 34456, 865,url));
        mDatas.add(new TestBean("Tome", "今天天气很好，出来钓鱼", R.drawable.ic_launcher_background, 2345, 98765,url));
        mDatas.add(new TestBean("Tome", "今天天气很好，出来钓鱼", R.drawable.ic_launcher_background, 87, 45,url));
        mDatas.add(new TestBean("Tome", "今天天气很好，出来钓鱼", R.drawable.ic_launcher_background, 2368435, 7587,url));
    }

    /**
     * 模拟刷新操作
     *
     * @param view
     */
    public void onRefresh(View view) {
        try {
            mNewDatas = new ArrayList<>();
            for (TestBean bean : mDatas) {
                mNewDatas.add(bean.clone());//clone一遍旧数据 ，模拟刷新操作
            }
            mNewDatas.get(0).setLookNumber((int) (Math.random() * 200));
            mNewDatas.get(0).setCommentNumber((int) (Math.random() * 200));
            mNewDatas.get(0).setContent(getRandomText());
            mNewDatas.get(0).setName(getRandomName());
            mNewDatas.get(1).setLookNumber((int) (Math.random() * 200));
            mNewDatas.get(1).setCommentNumber((int) (Math.random() * 200));
            mNewDatas.get(1).setContent(getRandomText());
            mNewDatas.get(1).setName(getRandomName());
            mNewDatas.get(2).setLookNumber((int) (Math.random() * 200));
            mNewDatas.get(2).setCommentNumber((int) (Math.random() * 200));
            mNewDatas.get(2).setContent(getRandomText());
            mNewDatas.get(2).setName(getRandomName());
            mNewDatas.get(3).setLookNumber((int) (Math.random() * 200));
            mNewDatas.get(3).setCommentNumber((int) (Math.random() * 200));
            mNewDatas.get(3).setContent(getRandomText());
            mNewDatas.get(3).setName(getRandomName());
            //利用DiffUtil.calculateDiff()方法，传入一个规则DiffUtil.Callback对象，和是否检测移动item的 boolean变量，得到DiffUtil.DiffResult 的对象
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //放在子线程中计算DiffResult
                    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(mDatas, mNewDatas), true);
                    Message message = mHandler.obtainMessage(1);
                    message.obj = diffResult;//obj存放DiffResult
                    message.sendToTarget();
                }
            }).start();
            //mAdapter.notifyDataSetChanged();//以前普通青年的我们只能这样，现在我们是文艺青年了，有新宠了

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //取出Result
                DiffUtil.DiffResult diffResult = (DiffUtil.DiffResult) msg.obj;
                //利用DiffUtil.DiffResult对象的dispatchUpdatesTo（）方法，传入RecyclerView的Adapter，轻松成为文艺青年
                diffResult.dispatchUpdatesTo(mAdapter);
                //将新数据设置给Adapter
                mDatas = mNewDatas;
                mAdapter.setData(mDatas);
                //老的数据刷新方法
               // mAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 生成随机文字的方法
     *
     * @return
     */
    private String getRandomText(){
        return "新的随机文本 " + (int) (Math.random() * 100);
    }

    /**
     * 随机名字
     * @return
     */
    private  String getRandomName(){
        return "新名字" + (int) (Math.random() * 100);
    }

}
